package manage.modules.mail.service.impl;

import manage.commons.Constants;
import manage.commons.utils.DateUtil;
import manage.commons.utils.MailUtil;
import manage.modules.BaseService;
import manage.modules.mail.model.MailBean;
import manage.modules.mail.model.MailHistory;
import manage.modules.mail.service.MailService;
import manage.modules.mail.util.MailType;

public class MailServiceImpl implements MailService {
	// 是否真实发送邮件
	private boolean realSend = false;
	private BaseService baseService;

	@Override
	public void sendMail(MailBean mailBean) {
		if (realSend) {
			if (null == mailBean.getMailType()) {
				mailBean.setMailType(MailType.SIMPLE);
			}
			try {
				MailHistory mailHistory = new MailHistory();
				mailBean.setFromEmailAddress(Constants.MAILSENDER);
				if (MailType.SIMPLE == mailBean.getMailType()) {
					MailUtil.sendSimpleEmail(mailBean.getSubject(),
							mailBean.getContents(),
							mailBean.getUserEmailAddress(),
							mailBean.getFromEmailAddress());
					mailHistory.setMailType("simple");
				} else if (MailType.HTML == mailBean.getMailType()) {
					MailUtil.sendHtmlEmail(mailBean.getSubject(),
							mailBean.getContents(),
							mailBean.getUserEmailAddress(),
							mailBean.getFromEmailAddress());
					mailHistory.setMailType("html");
				} else if (MailType.MultiPart == mailBean.getMailType()) {
					MailUtil.sendMultiPartEmail(mailBean.getSubject(),
							mailBean.getContents(),
							mailBean.getUserEmailAddress(),
							mailBean.getFromEmailAddress(),
							mailBean.getMultiPaths());
					mailHistory.setMailType("multipart");
				}
				mailHistory.setSubject(mailBean.getSubject());
				mailHistory.setContents(mailBean.getContents());
				mailHistory.setFormMail(mailBean.getFromEmailAddress());
				mailHistory.setSendTime(DateUtil.getCurrentDateTime());
				for (String toMail : mailBean.getUserEmailAddress()) {
					mailHistory.setToMail(toMail);
					insertMailHistory(mailHistory);
				}
			} catch (Exception e) {
				e.printStackTrace();
			}

		}
	}

	@Override
	public void insertMailHistory(MailHistory mailHistory) {
		baseService.insert(mailHistory);
	}

	public void setRealSend(boolean realSend) {
		this.realSend = realSend;
	}

	public void setBaseService(BaseService baseService) {
		this.baseService = baseService;
	}

	public BaseService getBaseService() {
		return baseService;
	}

}
